﻿using Blog.IService;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Blog.Mapping.BlogNewsDTO;
using BlogModel;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Authorization;
using SqlSugar;
using Newtonsoft.Json;
using System.Net;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860


/*

错误的请求结果 BadRequestResult 400
冲突结果 ConflictResult 409
没有内容结果 NoContentResult 204
没有找到结果 NotFoundResult 404
好的结果 OkResult 200
未经授权的结果 UnauthorizedResult 401
不可处理的实体结果 UnprocessableEntityResult 422
不支持的媒体类型结果 UnsupportedMediaTypeResult 415
内部服务器错误结果 InternalServerErrorResult 500
    return StatusCode((int)HttpStatusCode.InternalServerError, 你的定义类);
 */

/*
 * 通过 this.User 可以拿到用户请求携带的 token 信息
*/

/*
    使用缓存 memoryCache 减少数据库压力， 实现方法在control 上打上标识 [TypeFilter(typeof(FilterMemoryCacheAttribute))]
 */
namespace BlogSolution.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BlogNewsController : ControllerBase
    {
        private readonly IBlogNewsServer _blogNewsService;
        private readonly IMapper _mapper;
        public BlogNewsController(IBlogNewsServer blogNewsService, IMapper mapper)
        {
            this._blogNewsService = blogNewsService;
            _mapper = mapper;
        }
        // GET: api/<BlogNewsController>
        [HttpGet("GetBlogNews")]
        [TypeFilter(typeof(FilterMemoryCacheAttribute))]
        public async Task<ActionResult> GetBlogNews()
        {
            var data = await _blogNewsService.QueryAsync();
            if (data.Count() <= 0)
            {
                return NotFound("没有找到一条关于博客文章信息！");
            }
            return Ok(_mapper.Map<IEnumerable<BlogNewsGetDTO>>(data));
        }
        [HttpGet(Name = "GetBlogNewsPageList")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> GetBlogNewsPageList([FromQuery] PageModel pageModel)
        {
            var claim = this.User.FindFirst("id");
            if (claim == null)
            {
                return StatusCode((int)HttpStatusCode.Unauthorized, "没哟授权");
            }
            if (pageModel == null)
            {
                pageModel = new PageModel();
                pageModel.PageIndex = 1;
                pageModel.PageSize = 5;
            }
            //TO DO 这里的表达式怎么处理，如果在这写表达式 会不会把控制器搞得很复杂
            var data = await _blogNewsService.QueryPageListAsync(t => true, pageModel);
            if (data == null || data.Count() == 0)
            {
                return NotFound("博客信息列表不存在！");
            }
            var blogDto = _mapper.Map<IEnumerable<BlogNewsGetDTO>>(data);
            //添加头部分页信息
            Response.Headers.Add("x-PageInfo", JsonConvert.SerializeObject(
                //匿名类
                new
                {
                    pageModel,
                    totalPages = Math.Round(pageModel.PageCount * 1.0 / pageModel.PageSize),
                }
                )); ;
            return Ok(blogDto);
        }

        // GET api/<BlogNewsController>/5
        [HttpGet("{id}", Name = "GetNewsById")]
        public async Task<IActionResult> GetNewsById([FromRoute] int id)
        {
            var data = await _blogNewsService.FindAsync(id);
            if (data == null)
            {
                return NotFound($"没有找到ID={id}的博客文章。");
            }
            return Ok(_mapper.Map<BlogNewsGetDTO>(data));
        }

        // POST api/<BlogNewsController>
        [HttpPost]
        public async Task<IActionResult> CreateOneBlogNews([FromBody] BlogNewsCreateDTO blogNews)
        {
            var createData = _mapper.Map<BlogNews>(blogNews);
            if (createData == null)
            {
                return BadRequest();
            }
            bool flag = await _blogNewsService.AddAsync(createData);
            if (!flag)
            {
                return BadRequest();
            }
            return Created("GetNewsById", createData.ID);
        }

        // PUT api/<BlogNewsController>/5
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdataBlogNewsByID([FromRoute] int id, [FromBody] BlogNewsUpdataDTO blogDto)
        {
            var blogNewsDataFromResponse = await _blogNewsService.FindAsync(id);
            if (blogNewsDataFromResponse == null)
            {
                return NotFound($"要更新的资源ID={id}不存在");
            }
            _mapper.Map(blogDto, blogNewsDataFromResponse);
            await _blogNewsService.EditAsync(blogNewsDataFromResponse);
            return Ok();
        }

        [HttpPatch("{id}")]
        public async Task<IActionResult> PatchBlogNewsByIdAsync([FromRoute] int id, [FromBody] JsonPatchDocument<BlogNewsUpdataDTO> blogDto)
        {
            var blogNewsDataFromResponse = await _blogNewsService.FindAsync(id);
            if (blogNewsDataFromResponse == null)
            {
                return NotFound($"要更新的资源ID={id}不存在");
            }
            var blogNewsDataFromDto = _mapper.Map<BlogNewsUpdataDTO>(blogNewsDataFromResponse);

            blogDto.ApplyTo(blogNewsDataFromDto);
            _mapper.Map(blogNewsDataFromDto, blogNewsDataFromResponse);
            await _blogNewsService.EditAsync(blogNewsDataFromResponse);
            return Ok();
        }

        // DELETE api  [Authorize(Roles = "admin", AuthenticationSchemes = "Bearer")]
        [HttpDelete("{id}")]
        [Authorize(Roles = "root", AuthenticationSchemes = "Bearer")]
        public async Task<IActionResult> DeleteBlogNewsByID([FromRoute] int id)
        {
            var deleEntity = await _blogNewsService.FindAsync(id);
            if (deleEntity == null)
            {
                return NotFound($"要删除的ID={id}文章不存在！");
            }
            await _blogNewsService.DeletAsync(deleEntity);
            return NoContent();
        }
    }
}
